import { Feature } from 'ol';
import { Polygon } from 'ol/geom';

export class Ellipse extends Feature {
    constructor(coordinates) {
        super();
        this.coordinates = coordinates || [];
    }

    getGeometry() {
        try {
            console.log('Ellipse.getGeometry 被调用，坐标:', this.coordinates);
            if (this.coordinates.length < 2) {
                console.log('坐标点不足');
                return null;
            }

            const center = this.coordinates[0];
            const pnt2 = this.coordinates[1];

            // 计算半长轴长度（半径）
            const radius = Math.sqrt(
                Math.pow(pnt2[0] - center[0], 2) + 
                Math.pow(pnt2[1] - center[1], 2)
            );

            // 设置最小半径
            const minRadius = 0.0001;
            const actualRadius = Math.max(radius, minRadius);
            
            // 生成椭圆点集
            const points = [];
            const sides = 72;
            const rotation = Math.atan2(pnt2[1] - center[1], pnt2[0] - center[0]);
            
            const majorRadius = actualRadius;
            const minorRadius = actualRadius * 0.6;

            for (let i = 0; i <= sides; i++) {
                const angle = (i * 2 * Math.PI) / sides;
                const dx = majorRadius * Math.cos(angle);
                const dy = minorRadius * Math.sin(angle);
                const x = center[0] + dx * Math.cos(rotation) - dy * Math.sin(rotation);
                const y = center[1] + dx * Math.sin(rotation) + dy * Math.cos(rotation);
                points.push([x, y]);
            }

            points.push(points[0]);
            const polygon = new Polygon([points]);
            polygon.set('plotType', 'ellipse');
            console.log('生成椭圆几何体完成，点数:', points.length);
            return polygon;

        } catch (error) {
            console.error('椭圆计算错误:', error);
            return null;
        }
    }
}